package cn.woochen.mvvmframe.helper

import android.app.Activity
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.ProgressBar
import android.widget.TextView
import androidx.core.view.isInvisible
import cn.woochen.comlib.util.OnSingleClickListener
import cn.woochen.comlib.util.ext.setOnSingleClickListener
import cn.woochen.comlib.util.ext.showToast
import cn.woochen.mvvmframe.R
import cn.woochen.mvvmframe.bean.VersionBean
import cn.woochen.mvvmframe.util.SimpleDialogUtil
import cn.woochen.mvvmframe.util.logcom
import com.king.app.updater.AppUpdater
import com.king.app.updater.UpdateConfig
import com.king.app.updater.http.OkHttpManager
import com.king.app.updater.util.AppUtils
import java.io.File
import kotlin.math.roundToInt

class ApkUpdateHelper {

    private var mAppUpdater: AppUpdater? = null

    fun update(activity: Activity, updateVersionBean: VersionBean) {
        if (updateVersionBean.update == 0) return
        val canClose = updateVersionBean.update != 2
        val create = SimpleDialogUtil.create(activity, layoutRes = R.layout.dialog_force_update_apk, canceledOnTouchOutside = canClose)
        create?.apply {
            val tvTitle = getView<TextView>(R.id.tv_title)
            val tvContent = getView<TextView>(R.id.tv_content)
            val ll_operate = getView<LinearLayout>(R.id.ll_operate)
            val ll_operate2 = getView<LinearLayout>(R.id.ll_operate2)
            val ll_loading = getView<ViewGroup>(R.id.ll_loading)
            val bt2 = getView<TextView>(R.id.bt2)
            val tv_operate = getView<TextView>(R.id.tv_operate)
            val tv_progress = getView<TextView>(R.id.tv_progress)
            val tvVersionName = getView<TextView>(R.id.tv_version_name)
            val ivClose = getView<TextView>(R.id.iv_close)
            val progressBar = getView<ProgressBar>(R.id.progress)
            ll_operate?.visibility = View.VISIBLE
            ll_loading?.visibility = View.GONE
            ll_operate2?.visibility = View.GONE
            tvVersionName?.text = "（${updateVersionBean.versionNum}）"
            tvTitle?.text = updateVersionBean.title
            tvContent?.text = updateVersionBean.content
            ivClose?.isInvisible = updateVersionBean.update == 2
            ivClose?.setOnClickListener {
                dismiss()
            }
            bt2?.setOnSingleClickListener(object : OnSingleClickListener {
                override fun onSingleClick(v: View?) {
                    ll_operate?.visibility = View.GONE
                    ll_loading?.visibility = View.VISIBLE
                    ll_operate2?.visibility = View.GONE
                    val config = UpdateConfig()
                    config.isShowNotification = false
                    config.filename = "imoney.apk"
                    config.url = updateVersionBean.url
                    mAppUpdater = AppUpdater(activity, config).setHttpManager(OkHttpManager.getInstance())
                        .setUpdateCallback(object : com.king.app.updater.callback.UpdateCallback {

                            override fun onDownloading(isDownloading: Boolean) {
                                if (isDownloading) {
                                    showToast("已经在下载中,请勿重复下载。")
                                }
                            }

                            override fun onStart(url: String) {
                                progressBar?.progress = 0
                            }

                            override fun onProgress(progress: Long, total: Long, isChange: Boolean) {
                                if (isChange) {
                                    val currProgress = (progress * 1.0f / total * 100.0f).roundToInt()
                                    progressBar?.progress = currProgress
                                    tv_progress?.text = "${currProgress}%"
                                }
                            }

                            override fun onFinish(file: File) {
                                mFile = file
                                ll_operate?.visibility = View.GONE
                                ll_loading?.visibility = View.VISIBLE
                                progressBar?.progress = 100
                                tv_progress?.visibility = View.GONE
                                ll_operate2?.visibility = View.VISIBLE
                            }

                            override fun onError(e: Exception) {
                                logcom("下载失败：${e.message}")
                                showToast("การปรับปรุงล้มเหลว，${e.message}")
                                dismiss()
                            }

                            override fun onCancel() {
                                dismiss()
                            }
                        })
                    mAppUpdater?.start()
                }
            })
            tv_operate?.setOnSingleClickListener(object : OnSingleClickListener {
                override fun onSingleClick(v: View?) {
                    if (mFile != null && mFile?.exists()!!) {
                        AppUtils.installApk(activity, mFile, activity.packageName + ".fileProvider")
                    }
                }
            })
        }?.show()
    }

    private var mFile:File? = null
}